package info.cs52.fes.action.auth;

import info.cs52.fes.Application;
import info.cs52.fes.FesAction;
import info.cs52.fes.action.SessionUtils;
import info.cs52.fes.dao.UserDAO;
import info.cs52.fes.data.User;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class RegisterAction extends FesAction {

	private User userInfo;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (!"register".equals(req.getParameter("submit")) || !validate(req)) {
			return;
		}
		User user = new User();
		if ("register".equals(req.getParameter("submit"))) {
			user.setName(req.getParameter("name"));
			user.setEmail(req.getParameter("email"));
		}
		UserDAO.persist(user);
		SessionUtils.login(req, user);
		
		String returnUrl = req.getParameter("returnUrl");
		if (returnUrl == null) {
			returnUrl = Application.getPath();
		}
		resp.sendRedirect(returnUrl);
	}
	
	private static final Pattern EMAIL_PATTERN = Pattern.compile(
			"[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}", Pattern.CASE_INSENSITIVE); 
	
	private boolean validate(HttpServletRequest req) {
		if (StringUtils.isEmpty(req.getParameter("name"))) {
			message = "Tên người dùng là bắt buộc";
			return false;
		}
		if (!EMAIL_PATTERN.matcher(req.getParameter("email").trim()).matches()) {
			message = "Email không hợp lệ.";
			return false;
		}
		return true;
	}

	public User getUserInfo() {
		return userInfo;
	}
	
}
